﻿using System;
using VideoServices.Business.Facade;
using VideoServices.Domain.Entities;
using VideoServices.Services.Dto;
using VideoServices.Services.Interface;
using VideoServices.Services.Response;
using VideoServices.Services.Response.Extension;
using VideoServices.Services.Translation;
using VideoServices.Services.Translation.Base;
using VideoServices.Services.Translation.Factory;

namespace VideoServices.Services
{
    /// <summary>
    /// Exposes the the business layer as a WCF service.
    /// </summary>
    public class CustomerService : ICustomerService
    {
        #region Implementation of ICustomerService

        /// <summary>
        /// Gets the customer by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Response<CustomerDto> GetCustomerById(int id)
        {
            var response = new Response<CustomerDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoServicesFacade.Instance;
                Customer customer = facade.GetCustomerById(id);
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(CustomerTranslator));
                response.ResponseObject = translator.TranslateToDto<Customer, CustomerDto>(customer);
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error("Fatal error occured.", ex.Message));
            }
            return response;
        }

        /// <summary>
        /// Creates the customer.
        /// </summary>
        /// <param name="newCustomer">The new customer.</param>
        /// <returns></returns>
        public Response<CustomerDto> CreateCustomer(CustomerDto newCustomer)
        {
            var response = new Response<CustomerDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoServicesFacade.Instance;
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(CustomerTranslator));
                Customer customerEntity = translator.TranslateToEntity<CustomerDto, Customer>(newCustomer);
                Customer savedCustomer = facade.CreateCustomer(customerEntity);
                response.ResponseObject = translator.TranslateToDto<Customer, CustomerDto>(savedCustomer);
                response.Messages.AddSuccessfulSaveMessage("Customer");
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error("Fatal error occured.", ex.Message));
            }
            return response;
        }

        #endregion
    }
}